const Acan = require('../lib/Acan')
const { Worker } = require('worker_threads')
const pool = []
const pcount = { inc: 0 }
const worketCall = {
  0(rs) {
    console.log(0, rs)
  },
  1(rs) {
    for (const ns in rs) {
      tables[ns].inc = rs[ns]
    }
  }
}
const mod = {
  start() {
    const worker = new Worker(__dirname + '/thc.js')
    worker.inc = 11
    worker.on('message', (arr) => {
      const id = arr.shift()
      if (worketCall[id]) worketCall[id].apply(worketCall[id], arr)
      if (id > 10) delete worketCall[id]
    })
    worker.postMessage([0, 'conf', conf])
    for (const ns in tables) {
      if (ns !== 'tt.test') continue
      const o = {}
      const arr = [0, 'initTable']
      for (const key of Object.keys(tables[ns])) {
        if (['_sab', '_buf'].includes(key)) continue
        if (Acan.isFun(tables[ns][key])) continue
        o[key] = tables[ns][key]
      }
      arr.push(o)
      arr.push(Object.keys(tables[ns]._sab))
      for (const k of arr[3]) {
        arr.push(tables[ns]._sab[k])
      }
      worker.postMessage(arr)
    }
    pool.push(worker)
  },
  init(num) {
    for (let i = 0; i < num; i++) {
      mod.start()
    }
  },
  proxy(...args) {
    const worker = pool[pcount.inc]
    const id = worker.inc
    args.unshift(id)
    return new Promise(res => {
      worketCall[id] = (rs) => {
        res(rs)
        delete worketCall[id]
      }
      worker.postMessage(args)
      worker.inc++
      // pcount.inc++
      // if (pcount.inc >= pool.length) pcount.inc = 0
    })
  },
  proxyTable(...args) {
    args.unshift('table')
    return mod.proxy.apply(mod, args)
  }
}
module.exports = mod
